package com.mqqzt.douban;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gdata.data.TextContent;
import com.google.gdata.data.douban.Attribute;
import com.google.gdata.data.douban.NoteEntry;
import com.google.gdata.data.douban.NoteFeed;
import com.google.gdata.data.douban.UserEntry;
import com.mqqzt.douban.domain.Note;

public class MyNoteActivity extends BaseActivity implements OnClickListener {
	private ListView subjectlist;
	private Button bt_pre, bt_next;
	private MyNoteAdapter adapter;
	private boolean isLoading = false;
	private int startIndex;
	private int count;
	private ProgressDialog pd;
	private static final int NEW_NOTE = 0;
	private static final int EDIT_NOTE = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.my_note);
		super.onCreate(savedInstanceState);
		startIndex = 1;
		count = 10;
	}
	@Override
	public void setupView() {
		subjectlist = (ListView) this.findViewById(R.id.subjectlist);
		mTextViewTitle = (TextView) this.findViewById(R.id.myTitle);
		mRelativeLayoutLoading = (RelativeLayout) this.findViewById(R.id.loading);
		mImageBack = (ImageButton) this.findViewById(R.id.back_button);
		bt_pre = (Button) this.findViewById(R.id.bt_pre);
		bt_next = (Button) this.findViewById(R.id.bt_next);
	}

	@Override
	public void setListener() {
		mImageBack.setOnClickListener(this);
		bt_pre.setOnClickListener(this);
		bt_next.setOnClickListener(this);
		this.registerForContextMenu(subjectlist);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	                                ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.context_menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    int position = (int) info.id;
	    Note note = (Note) subjectlist.getItemAtPosition(position);
	    NoteEntry entry = note.getNoteEntry();
	    switch (item.getItemId()) {
	        case R.id.menu_add_note:
	            Intent newNoteIntent = new Intent(MyNoteActivity.this, NewNoteActivity.class);
	            startActivityForResult(newNoteIntent, NEW_NOTE);
	            return true;
	        case R.id.menu_edit_note:
	        	Intent editNoteintent = new Intent(MyNoteActivity.this, NewNoteActivity.class);
	        	editNoteintent.putExtra("iseditnote", true);
	        	MyApp myApp = (MyApp) getApplication();
	        	myApp.note = note;
	            startActivityForResult(editNoteintent, EDIT_NOTE);
	            return true;
	        case R.id.menu_delete_note:
	            deleteNote(entry);
	            return true;
	    }
		return super.onContextItemSelected(item);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == 200){
			startIndex = 1;
			fillData();
			if(requestCode == NEW_NOTE){
				Toast.makeText(MyNoteActivity.this, "发表新日记成功，正在刷新页面", Toast.LENGTH_SHORT).show();
			}else if(requestCode == EDIT_NOTE){
				Toast.makeText(MyNoteActivity.this, "更新日记成功，正在刷新页面", Toast.LENGTH_SHORT).show();
			}
		}
	}
	private void deleteNote(NoteEntry entry) {
		new AsyncTask<NoteEntry, Void, Boolean>(){
			
			@Override
			protected Boolean doInBackground(NoteEntry... params) {
				try {
					myService.deleteNote(params[0]);
					return true;
				} catch (Exception e) {
					return false;
				}
				
			}

			@Override
			protected void onPreExecute() {
				pd = new ProgressDialog(MyNoteActivity.this);
				pd.setMessage("正在删除日记");
				pd.show();
				super.onPreExecute();
			}

			@Override
			protected void onPostExecute(Boolean result) {
				pd.dismiss();
				if(result){
					fillData();
				}else{
					Toast.makeText(MyNoteActivity.this, "删除日记失败", Toast.LENGTH_SHORT).show();
				}
				super.onPostExecute(result);
			}
			
		}.execute(entry);
		
	}
	@Override
	public void fillData() {
		mTextViewTitle.setText("我的日记");
		if(isLoading){
			Toast.makeText(getApplicationContext(), "正在下载数据中", Toast.LENGTH_SHORT).show();
			return;
		}
		new AsyncTask<Void, Void, List<Note>>() {
			
			@Override
			protected void onPreExecute() {
				showLoading();
				isLoading = true;
				super.onPreExecute();
			}

			@Override
			protected void onPostExecute(List<Note> result) {
				hideLoading();
				if(result != null){
					adapter = new MyNoteAdapter(result);
					subjectlist.setAdapter(adapter);
				}else{
					Toast.makeText(MyNoteActivity.this, "从服务器获取数据异常", Toast.LENGTH_LONG).show();
				}
				isLoading = false;
				super.onPostExecute(result);
			}

			@Override
			protected List<Note> doInBackground(Void... params) {
				try {
					UserEntry ue = myService.getAuthorizedUser();
					String uid = ue.getUid();
					NoteFeed noteFeed = myService.getUserNotes(uid, startIndex, count);
					List<Note> notes = new ArrayList<Note>();
					for(NoteEntry noteEntry: noteFeed.getEntries()) {
						Note note = new Note();
						note.setNoteEntry(noteEntry);
						if(noteEntry.getContent() != null)
							note.setContent(((TextContent) noteEntry.getContent()).getContent().getPlainText());
						
						
						note.setTitle(noteEntry.getTitle().getPlainText());
					
						for (Attribute attr : noteEntry.getAttributes()) {
							if("privacy".equals(attr.getName())){
								note.setPrivacy(attr.getContent());
							}else if("can_reply".equals(attr.getName())){
								note.setCan_reply(attr.getContent());
							}
						}
						note.setPubdate(noteEntry.getPublished().toString());
						notes.add(note);
					}
					return notes;
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
			}
		}.execute();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_button:
			finish();
			break;
		case R.id.bt_pre:
			if(startIndex >= 11){
				startIndex = startIndex - count;
				fillData();
			}else{
				Toast.makeText(getApplicationContext(), "已经翻到了第一页", Toast.LENGTH_LONG).show();
			}
			
			break;
		case R.id.bt_next:
			startIndex = startIndex + count;
			fillData();
			break;
		}
		
	}
	
	private class MyNoteAdapter extends BaseAdapter{
		private List<Note> notes;
		
		public MyNoteAdapter(List<Note> notes) {
			this.notes = notes;
		}

		@Override
		public int getCount() {
			return notes.size();
		}

		@Override
		public Object getItem(int position) {
			return notes.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;
			if(convertView == null){
				view = View.inflate(getApplicationContext(), R.layout.note_item, null);
			}else{
				view = convertView;
			}
			TextView tv = (TextView) view.findViewById(R.id.fav_title);
			tv.setText(notes.get(position).getTitle());
			return view;
		}
		
	}

}
